// 完成权限管理的业务
const permModel = require('../model/permModel.js')
const roleModel = require('../model/roleModel.js')
const url = require('url');
// 定义全局数组，用来存放二级菜单树
let menuTree = []

// 完成角色对应权限数据的返回 （到二级权限）
module.exports.getPermByRid = (req, res) => {
	//1, 从token中获得角色id
	let {
		rid
	} = req.data;
	//2, 把角色对应的权限从所有权限表中过滤出来，返回 
	permModel.getAllPerm().then(result => {
		// 获得角色对应的权限id列表
		roleModel.getPsidsByRid(rid).then(resl => {
			// 把权限id列表由字符串转换为数组  split(',') 使字符串用逗号间隔开
			// let permids = resl[0].ps_ids.split(',')
			if (rid !== 0) {
				// 把权限id列表由字符串转换为数组  split(',') 使字符串用逗号间隔开
				let permids = resl[0].ps_ids.split(',')
				// 
				getPermTree(rid, permids, result);
			} else {
				// 角色id为0的为超级管理员，拥有所有权限，不用过滤
				getPermTree(rid, null, result);
			}
			// 把数据响应给vue
			res.send({
				data: menuTree,
				meta: {
					msg: '权限列表获取成功',
					status: 200
				}
			})
		})
	})
}

// 根据角色的权限id列表，生成二级菜单树
/* 
rid 登录用户的角色id
permArr 角色对应的权限id数组
result  所有的权限
 */
let getPermTree = (rid, permArr, result) => {
	// 先把数组清空，然后重新生成
	menuTree = [];
	// 生成一级菜单
	// 遍历所有的权限，把一级的过滤出来
	for (i in result) {
		let perm = result[i];
		// ps_level 为0  为一级权限菜单
		if (perm.ps_level == 0) {
			// 根据角色对应的权限id数组进行过滤
			// 判断权限id数组中是否包含本次循环的权限id，不包含直接跳出本次循环
			// 不向菜单数组中存储
			if (rid !== 0) {
				// indexOf()返回元素在数组中的下标，如果数组中没有这个元素则返回为-1   continue跳出本次循环，进行下次循环
				if (permArr.indexOf(perm.ps_id + '') < 0) continue;
			}
			menuTree.push({
				"id": perm.ps_id,
				"authName": perm.ps_name,
				"path": perm.ps_api_path,
				"children": []
			})
		}
	}
	//生成二级菜单
	//遍历一级菜单数组，边遍历边把二级菜单存到一级菜单里边
	for (i in menuTree) {
		let childTree = menuTree[i].children;
		//遍历所有权限，把二级权限过滤出来，对应的填充到一级权限菜单里
		for (j in result) {
			let per = result[j];
			//除了是一级菜单外，还要是本次循环中的一级菜单对应的二级菜单
			if (per.ps_level == 1 && per.ps_pid == menuTree[i].id) {
				if (rid !== 0) {
					if (permArr.indexOf(per.ps_id + '') < 0) continue;
				}
				childTree.push({
					"id": per.ps_id,
					"authName": per.ps_name,
					"path": per.ps_api_path,
					"children": []
				})
			}
		}
	}

}

//按页获取权限
module.exports.getAllPerm = async (req, res) => {
	let {
		query
	} = url.parse(req.url, true);
	let {
		pagenum,
		pagesize
	} = query;
	pagenum = parseInt(pagenum);
	pagesize = parseInt(pagesize);
	let count = await permModel.getPermCount();
	count = count[0].cou;
	//获取总页数
	let totalPage = Math.ceil(count / pagesize);
	//计算起始下标
	let offset = (pagenum - 1) * pagesize;
	if (offset >= count) {
		pagenum = 1;
		offset = 0;
	}
	//定义给sql语句传参的数组
	let pageInfo = [offset, pagesize];
	let result = await permModel.getPermByPage(pageInfo);
	//遍历结果集,把数据存到数组里边
	let perms = [];
	for (i in result) {
		let perm = result[i];
		perms.push({
				"id": perm.ps_id,
				"authName": perm.ps_name,
				"level": perm.ps_level,
				"pid": perm.id,
				"path": perm.ps_api_path
		})
	}
	res.send({
		data: {
			'totalPage': totalPage,
			'total': count,
			'pagenum': pagenum,
			'perms': perms,
		},
		meta: {
			'msg' : '数据权限列表获取成功',
			'status': 200
		}
	})
}

//返回树状结构的三级权限
module.exports.getAllPermTree = async (req,res) =>{
	let permes = await permModel.getAllPerm();
	let permTree = ThreeTree(permes);
	res.send({
		data: permTree,
		meta: {
			msg: '权限树获取成功',
			status: 200
		}
	})
}

// 生成三级菜单树
ThreeTree = (permes) =>{
	let permtree = [];
	for (i in permes) {
		let perm = permes[i];
		if (perm.ps_level == 0) {
			permtree.push({
					"id": perm.ps_id,
					"authName": perm.ps_name,
					"path": perm.ps_api_path,
					"children": []
			})
		}
	}
	//生成二级菜单
	//遍历每一项的一级菜单，把二级菜单对应的填进去
	for( i in permtree){
		let permPar = permtree[i];
		//遍历所有的权限，把二级权限过滤出，对应导的填充到一级权限里边
		for(j in permes) {
			let perm =  permes[j];
			//除了过滤出二级菜单，还要把一级菜单和二级菜单对应上
			if (perm.ps_level == 1 && perm.ps_pid == permPar.id ) {
				permtree[i].children.push({
						"id": perm.ps_id,
						"authName": perm.ps_name,
						"path": perm.ps_api_path,
						"children": []
				})
			}
		}
	}
	
	//生成三级菜单， 
	for(i in permtree){
		for(j in permtree[i].children){
			let secMenu = permtree[i].children[j];
			for( id in permes) {
				let perm = permes[id];
				if(perm.ps_level == 2 && perm.ps_pid == secMenu.id){
					permtree[i].children[j].children.push({
						"id": perm.ps_id,
						"authName": perm.ps_name,
						"path": perm.ps_api_path,
					})
				}
			}
		}
	}
	
	return permtree;
}

